package org.anupta.realm.server.realm.packet.login;

import org.anupta.realm.entity.dao.DAO;
import org.anupta.realm.entity.entities.Account;
import org.anupta.realm.main.Main;
import org.anupta.realm.server.realm.client.RealmClient;
import org.anupta.realm.server.realm.client.RealmClient.State;
import org.anupta.realm.server.realm.packet.RealmPacket;
import org.anupta.realm.server.realm.packet.login.answer.AccountCommunity;
import org.anupta.realm.server.realm.packet.login.answer.AccountIsAdmin;
import org.anupta.realm.server.realm.packet.login.answer.AccountPseudo;
import org.anupta.realm.server.realm.packet.login.answer.AccountQuestion;
import org.anupta.realm.server.realm.packet.login.answer.HostList;
import org.anupta.realm.server.realm.packet.login.answer.InvalidAccount;
import org.anupta.realm.server.realm.packet.other.ConnectionError;
import org.anupta.realm.utils.others.Utils;

public class Login extends RealmPacket {
	private StringBuilder username = new StringBuilder();
	private StringBuilder password = new StringBuilder();

	public Login(RealmClient client, String message) {
		super(client,message);
		unpack();
		doPacket();
	}

	@Override
	public void unpack() {
		username.append(packetIn.toString().split("\n")[0]);
		password.append(packetIn.toString().split("\n")[1]);
	}
	
	@Override
	public void pack() {
	}

	@Override
	public void doPacket() {
		if(!(password.toString().startsWith("#1"))){
			new ConnectionError(client);
			client.quit();
			return;
		}
		String hashPass = password.substring(2);
		Account account = DAO.getDao(Account.class).find(username.toString());
		//TODO: Condition
		if(account == null){
			new InvalidAccount(client);
			client.quit();
			return;
		}
		//TODO: isOnline,ban time
		if(!hashPass.equals(Utils.getCryptedPassword(client.getHash(), account.getPassword()))){
			new InvalidAccount(client);
			client.quit();
			return;
		}
		client.setAccount(account);
		client.setState(State.GAMESERVER);
		new AccountPseudo(client);
		new AccountCommunity(client);
		new HostList(client);
		new AccountIsAdmin(client);
		new AccountQuestion(client);
		Main.out.println(new StringBuilder(client.getIp()).append(" is connected").toString());
	}
}
